//
//  ContractAddNew.m
//  Opper
//
//  Created by Le Dung on 4/14/13.
//  Copyright (c) 2013 LeDung. All rights reserved.
//

#import "ContractAddNew.h"

@interface ContractAddNew ()

@end

@implementation ContractAddNew
@synthesize containView;

@synthesize isMove,isSetAlert;
@synthesize categoryArray,productArray,providerArray;
@synthesize idCategory,idProvider;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
-(void)viewDidAppear:(BOOL)animated
{
    [StyleClass barButtonItemEdit:self left:YES right:NO];
}
-(void)rightPress
{
    
}

-(void)leftPress
{
    [self.navigationController popViewControllerAnimated:YES];
}


// 100 : category ;  101 : provider ;  102 : product
-(void)indexPress:(NSString *)stringRespone andTagRespone:(NSInteger)tagR andIndexObject:(NSString *)idRespone andNameRespone:(NSString *)nameRespone
{
    
    UIButton *button =(UIButton*)[self.view viewWithTag:tagR];
    [button setTitle:nameRespone forState:UIControlStateNormal];
    
    if(tagR==100||tagR==101)
    {
        if(tagR==100)
        {
            self.idCategory =idRespone;
            [self.productList setTitle:@"" forState:UIControlStateNormal];
        }
        if(tagR==101)
        {
            self.idProvider=idRespone;
            [self.productList setTitle:@"" forState:UIControlStateNormal];
        }
        if(self.idCategory && self.idProvider)
        {
            [self createProductView:self.idCategory andProviderId:self.idProvider];
        }
    }
    
    else
    {
        self.idProduct=idRespone;
    }
}

-(void)gotoMainScreen
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    [StyleClass background:self.view];

    [StyleClass createNavi:self andTitle:@"Abonnementem"];
    [self styleContaint];
    [self loadData];
    [self buttonTarget];
    [self createListCollection];

 
    [self createPicker];
    
    self.productNumber.delegate=self;
    if(self.isAddContract==0)
    {
        self.terminalSwitch.userInteractionEnabled =NO;
    }
}

-(void)createPicker
{
    self.starDateP =[[UIDatePicker alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];
    [self.starDateP setDatePickerMode:UIDatePickerModeDate];
    [self.containView addSubview:self.starDateP];
    [self.starDateP setHidden:YES];
    [self.starDateP addTarget:self action:@selector(dateChange) forControlEvents:UIControlEventValueChanged];
    
}
-(void)loadData
{
    self.categoryArray =[[[NSMutableArray alloc]init] autorelease];
    self.providerArray =[[[NSMutableArray alloc]init] autorelease];
    self.productArray =[[[NSMutableArray alloc]init] autorelease];
    [self loadCategory];
    [self loadProvider];
    
    for(CategoryClass *categoryUnit in [GetData App].catagoryArray)
    {
        if([categoryUnit.idAutoIncr isEqualToString:self.contractUnit.categoryId])
        {
            [self.categoryList setTitle:categoryUnit.categoryName forState:UIControlStateNormal];
        }
    }
    [self.productList setTitle:self.contractUnit.productName forState:UIControlStateNormal];
    [self.providerList setTitle:self.contractUnit.providerName forState:UIControlStateNormal];
    
    self.productNumber.text =self.contractUnit.contractNumber;
    [self.startDate setTitle:self.contractUnit.contractStartDate forState:UIControlStateNormal];
    [self.endDate setTitle:self.contractUnit.contractEndDate forState:UIControlStateNormal];
    
    [self.terminalSwitch setOn:NO];
    if([self.contractUnit.terminalAlert isEqualToString:@"1"]) [self.terminalSwitch setOn:YES];
    
    
}

-(void)loadCategory
{
    for(CategoryClass *unit in [GetData App].catagoryArray)
    {
        ListObject *listObject =[[ListObject alloc]init];
        listObject.objectName = unit.categoryName;
        listObject.objectId =unit.idAutoIncr;
        [self.categoryArray addObject:listObject];
        [listObject release];
    }
}

-(void)loadProvider 
{
    for(ProviderClass *unit in [GetData App].providerArray)
    {
        ListObject *listObject =[[ListObject alloc]init];
        listObject.objectName = unit.providerName;
        listObject.objectId =unit.idAutoIncr;
        [self.providerArray addObject:listObject];
        [listObject release];
        
    }
     
}
-(void )createProductView:(NSString*)categoryId andProviderId:(NSString*)providerId
{
    
    self.productArray =[GetData productFilter:self.productArray andCategoryId:categoryId andProviderId:providerId];
    ListCollection *product=(ListCollection*)[self.view viewWithTag:202];
    [product removeFromSuperview];
    
    product=[StyleClass listCollection:self.containView andViewLocation:[self.view viewWithTag:102] andData:self.productArray andTagSender:102 ];
    product.tag=202;
    product.delegate=self;
}




-(void)createListCollection
{
    ListCollection *catalog=
    [StyleClass listCollection:self.containView andViewLocation:[self.view viewWithTag:100] andData:self.categoryArray andTagSender:100 ];
    catalog.tag=200;
    
    catalog.delegate =self;
    
    ListCollection *provider =[StyleClass listCollection:self.containView andViewLocation:[self.view viewWithTag:101] andData:self.providerArray andTagSender:101 ];
    provider.tag=201;
    provider.delegate=self;

}
-(void)buttonTarget
{
    //Opslaan       annuleren cancel
    
    [self.acceptButton setBackgroundImage:[StyleClass nGreen] forState:UIControlStateNormal];
    [self.acceptButton addTarget:self action:@selector(acceptPress) forControlEvents:UIControlEventTouchUpInside];
    [self.cancelButton setBackgroundImage:[StyleClass nRed] forState:UIControlStateNormal];
    [self.cancelButton addTarget:self action:@selector(cancelPress) forControlEvents:UIControlEventTouchUpInside];
    
    [self.categoryList setBackgroundImage:[StyleClass nList] forState:UIControlStateNormal];
    [self.providerList setBackgroundImage:[StyleClass nList] forState:UIControlStateNormal];
    [self.productList setBackgroundImage:[StyleClass nList] forState:UIControlStateNormal];
    [self.startDate setBackgroundImage:[StyleClass nList] forState:UIControlStateNormal];
    [self.endDate setBackgroundImage:[StyleClass nList] forState:UIControlStateNormal];
    
    
    self.categoryList.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    self.providerList.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    self.productList.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    self.startDate.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    self.endDate.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    
    
    [self.categoryList addTarget:self action:@selector(listCollectionPress:) forControlEvents:UIControlEventTouchUpInside];
    [self.providerList addTarget:self action:@selector(listCollectionPress:) forControlEvents:UIControlEventTouchUpInside];
    [self.productList addTarget:self action:@selector(listCollectionPress:) forControlEvents:UIControlEventTouchUpInside];
    
    
    
    
    [self.startDate addTarget:self action:@selector(pickerPress:) forControlEvents:UIControlEventTouchUpInside];
    self.startDate.tag=300;
    self.endDate.tag=301;
    [self.endDate addTarget:self action:@selector(pickerPress:) forControlEvents:UIControlEventTouchUpInside];
    self.productNumber.borderStyle=UITextBorderStyleNone;
    [self.productNumber setBackground:[StyleClass nText]];
    

}

-(void)dateChange
{
    NSDate *currDate = [self.starDateP date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd"];
    NSString *dateString = [dateFormatter stringFromDate:currDate];
    
    if(self.isStartDate)
    {
        [self.startDate setTitle:dateString forState:UIControlStateNormal];
    }
    else
    {
        [self.endDate setTitle:dateString forState:UIControlStateNormal];

    }
}

-(void)pickerPress:(UIButton*)button
{
    self.starDateP.hidden? [self.starDateP setHidden:NO]:[self.starDateP setHidden:YES];
    if(button.tag==300)
    {
        self.isStartDate=1;
    }
    else
    {
        self.isStartDate=0;
    }
        
    
    
    CGRect frame =button.frame;
    frame.size.width=300;
    frame.origin.x=0;
    frame.origin.y=0;
    self.starDateP.frame =frame;

}

-(void)acceptPress
{
    
    if(self.isAddContract==0)
    {
    ContractInfo *contract =[[ContractInfo alloc]init];
    
    contract.memberId =self.member.idMember; 
    contract.contractNumber=self.productNumber.text;
    contract.categoryId  =self.idCategory;
    contract.productId=self.idProduct;
    contract.providerId =self.idProvider;
    contract.contractStartDate=self.startDate.titleLabel.text;
    contract.contractEndDate =self.endDate.titleLabel.text;
    
    NSString *functionName =@"addContract";
    NSMutableDictionary *dictionary =[[[NSMutableDictionary alloc]init] autorelease];
    [dictionary setValue:[GetData App].userAccount.userName forKey:@"username"];
    [dictionary setValue:[GetData App].userAccount.password forKey:@"passwd"];
    [dictionary setValue:self.member.idMember forKey:@"member_id"];
    [dictionary setValue:self.productNumber.text forKey:@"contract_number"];
    [dictionary setValue:contract.categoryId forKey:@"category_id"];
    [dictionary setValue:contract.providerId forKey:@"provider_id"];
    [dictionary setValue:contract.productId forKey:@"product_id"];
    [dictionary setValue:contract.contractStartDate forKey:@"start_date"];
    [dictionary setValue:contract.contractEndDate forKey:@"end_date"];

    NSString *jsonRespones =[GetData sendRequest:functionName andDictionary:dictionary];
        if(jsonRespones)
    {
        if(![GetData checkError:jsonRespones])
        {
            [self.navigationController popViewControllerAnimated:YES];
        }
        else
        {
            [StyleClass warningShow:nil andMassage:[GetData checkMassage:jsonRespones]];
        }
    }

    }
    
    
    if(self.isAddContract ==-1)
    {
        
        ContractInfo *contract =[[ContractInfo alloc]init];
        contract.memberId =self.member.idMember;
        
        contract.contractNumber=[ContractAddNew dataEdit:self.productNumber.text andOld:self.contractUnit.contractNumber];
        contract.categoryId =[ContractAddNew dataEdit:self.idCategory andOld:self.contractUnit.categoryId];
        contract.productId =[ContractAddNew dataEdit:self.idProduct andOld:self.contractUnit.productId];
        contract.providerId =[ContractAddNew dataEdit:self.idProvider andOld:self.contractUnit.providerId];
        contract.contractStartDate=self.startDate.titleLabel.text;
        contract.contractEndDate =self.endDate.titleLabel.text;
        
        NSString *functionName =@"updateContract";
        NSMutableDictionary *dictionary =[[[NSMutableDictionary alloc]init] autorelease];
        [dictionary setValue:[GetData App].userAccount.userName forKey:@"username"];
        [dictionary setValue:[GetData App].userAccount.password forKey:@"passwd"];
        [dictionary setValue:self.member.idMember forKey:@"member_id"];
        [dictionary setValue:self.productNumber.text forKey:@"contract_number"];
        [dictionary setValue:contract.contractId forKey:@"contract_id"];
        [dictionary setValue:contract.categoryId forKey:@"category_id"];
        [dictionary setValue:contract.providerId forKey:@"provider_id"];
        [dictionary setValue:contract.productId forKey:@"product_id"];
        [dictionary setValue:contract.contractStartDate forKey:@"start_date"];
        [dictionary setValue:contract.contractEndDate forKey:@"end_date"];
        
        NSString *jsonRespones =[GetData sendRequest:functionName andDictionary:dictionary];
        if(jsonRespones )
        {
            if(![GetData checkError:jsonRespones])
            {
                [self.navigationController popViewControllerAnimated:YES];
            }
            else
            {
                [StyleClass warningShow:nil andMassage:[GetData checkMassage:jsonRespones]];
            }

        }
        
        

    }
}


+(NSString*)dataEdit:(NSString*)newData andOld:(NSString*)oldData
{
    if(newData.length>0)
        return newData;
    return oldData;
    
}
-(void)cancelPress
{
    
}

-(void)styleContaint
{
    [self.containView setBackgroundColor:[UIColor whiteColor]];
    self.containView.layer.shadowColor = [[UIColor blackColor] CGColor];
    self.containView.layer.shadowOffset = CGSizeMake(0.0, 2.0);
    self.containView.layer.shadowOpacity = 1.0f;
}


//field contron tag -> 100 - 150


-(IBAction)switchChange:(id)sender
{
    UISwitch *switchV =(UISwitch*)sender;
    if([switchV isOn])
    {
        AlertControl *page=[[[AlertControl alloc]init]autorelease];
        [StyleClass currentScreen:self andDestination:page andHideBackButton:YES];
    
    }
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

-(IBAction)listCollectionPress:(id)sender
{
    UIButton *button =(UIButton*)sender;

    UIView *view = [self.view viewWithTag:button.tag+100];
    if(view.hidden)
    {
        [view setHidden:NO];
    }
    else
    {
        [view setHidden:YES];
    }
}
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
   
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)dealloc
{
    [_categoryList release];
    [_providerList release];
    [_productList release];
    [_productNumber release];
    [_startDate release];
    [_endDate release];
    [_terminalSwitch release];
    [_acceptButton release];
    [_cancelButton release];
    [super dealloc];
    [categoryArray release];
    [productArray release];
    [containView release];

}

@end
